package mysrpringboot.springboot.Service.impl;

import com.alibaba.fastjson.JSON;
import mysrpringboot.springboot.Dao.PositionDao;
import mysrpringboot.springboot.Service.PositionService;
import mysrpringboot.springboot.pojo.Position;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;


@Service
public class PositionServiceImpl implements PositionService {
    private  static  final Logger logger = LogManager.getLogger(PositionServiceImpl.class);


    private  static  final  String  POSITION_INDEX = "position";
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private PositionDao positionDao;
    @Override
    public List<Map<String, Object>> searchPos(String keyword) throws IOException {
        ArrayList<Map<String,Object>>  list = new ArrayList<>();
        // 搜索
        SearchRequest searchRequest = new SearchRequest(POSITION_INDEX);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        QueryBuilder builder = QueryBuilders.matchQuery("positionName",keyword);
        searchSourceBuilder.query(builder);
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
        // 执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);

        SearchHit[]  hits = searchResponse.getHits().getHits();
        for (SearchHit hit:hits){
            list.add(hit.getSourceAsMap());
        }

        if(list.size()<5){
            QueryBuilder builder1 = QueryBuilders.matchQuery("positionAdvantage",keyword);
            searchSourceBuilder.query(builder1);
            searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
            // 执行搜索
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse1 = client.search(searchRequest,RequestOptions.DEFAULT);
            SearchHit[]  hits1 = searchResponse1.getHits().getHits();
            for (SearchHit hit:hits1){
                list.add(hit.getSourceAsMap());
            }
        }
        return   list;
    }


    @Override
    public void importAll() throws IOException {
        writeMySQLDataToES();
    }

    private   void  writeMySQLDataToES() {
        BulkProcessor bulkProcessor = getBulkProcessor(client);
        List<Position> dataList = positionDao.findAll();
        dataList.forEach(a -> {
            HashMap<String,String> map = JSON.parseObject(JSON.toJSONString(a), HashMap.class);
            bulkProcessor.add(new IndexRequest(POSITION_INDEX).source(map));
        });


        bulkProcessor.flush();

    }
    private BulkProcessor getBulkProcessor(RestHighLevelClient client) {

        BulkProcessor bulkProcessor = null;
        try {

            BulkProcessor.Listener listener = new BulkProcessor.Listener() {
                @Override
                public void beforeBulk(long executionId, BulkRequest request) {
                    logger.info("Try to insert data number : "
                            + request.numberOfActions());
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request,
                                      BulkResponse response) {
                    logger.info("************** Success insert data number : "
                            + request.numberOfActions() + " , id: " + executionId);
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
                    logger.error("Bulk is unsuccess : " + failure + ", executionId: " + executionId);
                }
            };

            BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer = (request, bulkListener) -> client
                    .bulkAsync(request, RequestOptions.DEFAULT, bulkListener);

            BulkProcessor.Builder builder = BulkProcessor.builder(bulkConsumer, listener);
            builder.setBulkActions(5000);
            builder.setBulkSize(new ByteSizeValue(100L, ByteSizeUnit.MB));
            builder.setConcurrentRequests(10);
            builder.setFlushInterval(TimeValue.timeValueSeconds(100L));
            builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1L), 3));
            // 注意点：让参数设置生效
            bulkProcessor = builder.build();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                bulkProcessor.awaitClose(100L, TimeUnit.SECONDS);
            } catch (Exception e1) {
                logger.error(e1.getMessage());
            }
        }
        return bulkProcessor;
    }
}
